package com.shiwaixiangcun.authz.shiro.strategy;

import com.shiwaixiangcun.authz.shiro.realm.OAuth2Realm;
import com.shiwaixiangcun.core.shiro.exception.OAuth2TokenAuthenticationException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy;
import org.apache.shiro.realm.Realm;

public class MkAtLeastOneSuccessfulStrategy extends AtLeastOneSuccessfulStrategy {

    @Override
    public AuthenticationInfo afterAttempt(Realm realm, AuthenticationToken token, AuthenticationInfo singleRealmInfo, AuthenticationInfo aggregateInfo, Throwable t) throws AuthenticationException {
        AuthenticationInfo info;
        // 防止OAuth2TokenAuthenticationException被覆盖
        if (realm instanceof OAuth2Realm && aggregateInfo == null && t != null) {
            if (t instanceof OAuth2TokenAuthenticationException) {
                //propagate:
                throw ((OAuth2TokenAuthenticationException) t);
            } else {
                String msg = "Unable to acquire account data from realm [" + realm + "].  The [" +
                        getClass().getName() + " implementation requires all configured realm(s) to operate successfully " +
                        "for a successful authentication.";
                throw new AuthenticationException(msg, t);
            }
        }

        if (singleRealmInfo == null) {
            info = aggregateInfo;
        } else {
            if (aggregateInfo == null) {
                info = singleRealmInfo;
            } else {
                info = merge(singleRealmInfo, aggregateInfo);
            }
        }

        return info;
    }


}
